package com.kingtone.rongji;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.fragment.BaseFragment;
import com.kingtone.rongji.fragment.CartFragment;
import com.kingtone.rongji.fragment.CategoryFragment;
import com.kingtone.rongji.fragment.DashboardFragment;
import com.kingtone.rongji.fragment.IBaseFragment;
import com.kingtone.rongji.fragment.LeftCategoryFragment;
import com.kingtone.rongji.fragment.SearchFragment;
import com.kingtone.rongji.fragment.SearchFragment.OnSearchQueryChangeListener;
import com.kingtone.rongji.fragment.StackFragment;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.CartUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.kingtone.rongji.ui.BadgeView;

public class MainActivity extends SlidingFragmentActivity implements
		OnTabChangeListener, OnSearchQueryChangeListener, IBaseFragment {
	
	private String TAG = "MainActivity";
	
	private BaseFragment mFragment;
	
	private Bundle mBundle;

	private SlidingMenu sm;

	private LeftCategoryFragment mLeftMenu;

	private MainActivity context;

	private FragmentTabHost tabhost;

	private FrameLayout shopCartImageView;

	private LayoutInflater inflater;

	private int totalCounts;
	
	private BadgeView badge;
	
	@SuppressWarnings("rawtypes")
	private Class fragment[] = { DashboardFragment.class,
			CategoryFragment.class, StackFragment.class,
			SearchFragment.class, CartFragment.class };

	private int tgBgs[] = { R.drawable.bg_tab_dashboard_selector,
			R.drawable.bg_tab_category_selector,
			R.drawable.bg_tab_profile_selector,
			R.drawable.bg_tab_search_selector,
			R.drawable.bg_tab_category_selector };

	private String tabStrs[] = { "Dashboard", "Category", "Profile", "Search",
			"Cart" };

	private String lastTabId = tabStrs[0];

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		createLeftMenu();
		setContentView(R.layout.activity_main);
		context = this;
		inflater = LayoutInflater.from(context);
		initView();
		Intent intent = getIntent();
		if(intent.hasExtra("isCancelOrder") && intent.getBooleanExtra("isCancelOrder", false))
		{
			setCurrentTab("Profile", null);
		}
	}

	private void createLeftMenu() {
		sm = getSlidingMenu();
		setBehindContentView(R.layout.fragment_left_category);
		sm.setSecondaryMenu(R.layout.fragment_left_category);
		mLeftMenu = new LeftCategoryFragment();
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_left_frag, mLeftMenu, "Left").commitAllowingStateLoss();
		sm.setFadeDegree(0.35f);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		sm.setMode(SlidingMenu.LEFT);
	}

	private void initView() {
		tabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		tabhost.setup(context, getSupportFragmentManager(), R.id.realtabcontent);
		tabhost.getTabWidget().setDividerDrawable(null);
		for (int i = 0; i < fragment.length; i++) {
			TabSpec tabSpec = tabhost.newTabSpec(tabStrs[i]).setIndicator(
					getTabView(i));
			tabhost.addTab(tabSpec, fragment[i], null);
		}
		tabhost.setOnTabChangedListener(context);
		shopCartImageView = (FrameLayout) findViewById(R.id.shopcartImage);
		shopCartImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(MainActivity.this, CartActivity.class);
				startActivity(intent);
			}
		});
		
		View cartImage = this.findViewById(R.id.shopcartImage);
		badge = new BadgeView(this, cartImage);
	}

	public View getTabView(int index) {
		View view;
		if (index == 4) {
			view = new TextView(context);
		} else {
			view = inflater.inflate(R.layout.tab_view, null);
			ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
			iv_icon.setImageResource(tgBgs[index]);
		}
		return view;
	}

	@Override
	public void onTabChanged(String tabId) {
		if ("Profile".equals(tabId)) {
			if(!SharedPreferencesUtil.getInstance(context).getBoolean(
					AppContasts.IS_LOGINED_KEY))
			{
				Intent intent = new Intent(this, LoginActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
			}
		}
		lastTabId = tabId;
	}
	
	private static Boolean isQuit = false;
	
	private Timer timer = new Timer();
	
	private void closeProject() {
		if (isQuit == false) {
			isQuit = true;
			Toast.makeText(getBaseContext(), "再次点击确定退出软件", Toast.LENGTH_SHORT).show();
			TimerTask task = null;
			task = new TimerTask() {
				@Override
				public void run() {
					isQuit = false;
				}
			};
			timer.schedule(task, 2000);
			return;
		} else {
			exitApplication();
			return;
		}
	}

	private void exitApplication() {
		ShareSDK.stopSDK(this.getApplicationContext());
		RongJiApplication application = RongJiApplication.getInstance();
		application.exitApp();
	}

	/**
	 * 返回键
	 */
	public void onBackPressed() {
		if(mFragment != null && mFragment.onBackPressed())
		{
			return;
		}
		closeProject();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		updateBadge(0, false);
	}
	
	public void logout() {
		SharedPreferencesUtil.getInstance(context).delete(AppContasts.IS_LOGINED_KEY);
		SharedPreferencesUtil.getInstance(context).delete(AppContasts.USERID_KEY);
	}
	
	public void updateBadge(int count, boolean isAdd)
	{
		List<Product> datas = CartUtils.getAllProductsForCart(context);
		int c = 0;
		for(Product item:datas) {
			c+=item.getQuantity();
		}
		this.totalCounts = c;
		
		View empty = shopCartImageView.findViewById(R.id.shop_cart_empty);
		View full = shopCartImageView.findViewById(R.id.shop_cart_full);
		if(this.totalCounts > 0)
		{
			badge.setText("" + totalCounts);
			badge.show();
			empty.setVisibility(View.INVISIBLE);
			full.setVisibility(View.VISIBLE);
		}
		else
		{
			badge.hide();
			empty.setVisibility(View.VISIBLE);
			full.setVisibility(View.INVISIBLE);
		}
	}
	
	public void setCurrentTab(String tag, Bundle bundle){
		this.mBundle = bundle;
		tabhost.setCurrentTabByTag(tag);
	}

	@Override
	public void setFragment(BaseFragment fragment) {
		// TODO Auto-generated method stub
		this.mFragment = fragment;
	}
	
	@Override
	public void onQueryChanged(int catgeoryId, String keyWord, boolean currentTab) {
		Bundle bundle = new Bundle();
		bundle.putString("KeyWord", keyWord);
		bundle.putInt("catgeoryId", catgeoryId);
		setCurrentTab("Search", bundle);
		if(currentTab)
		{
			Fragment oldFragment = getSupportFragmentManager().findFragmentByTag("Search");
			if(oldFragment != null && oldFragment instanceof SearchFragment)
			{
				((SearchFragment) oldFragment).initData();
			}
			if(sm != null)
			{
				sm.toggle();
			}
		}
	}

	public Bundle getBundle() {
		return mBundle;
	}
	
	public void setBundle(Bundle bundle) {
		this.mBundle = bundle;
	}
}
